package com.ttl.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ttl.web.entity.*;
import com.ttl.web.service.GoodsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ttl.web.utils.ResultVo;

import java.util.Date;
import java.util.Optional;

/**
 * 失物招领商品管理
 * @author 上玄
 */
@RestController
@RequestMapping("/api/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    /**
     * 发布商品
     */
    @PostMapping("/release")
    public ResultVo add(@RequestBody Goods goods) {
        System.out.println(goods);
        goods.setCreateTime(new Date());
        if (goodsService.save(goods)) {
            return ResultVo.success("发布成功");
        }else {
            return ResultVo.error("发布失败");
        }
    }

    /**
     * 编辑商品
     * @param goods
     * @return
     */
    @PutMapping
    public ResultVo edit(@RequestBody Goods goods) {
        if (goodsService.updateById(goods)) {
            return ResultVo.success("编辑成功");
        }else {
            return ResultVo.error("编辑失败");
        }
    }

    /**
     * 删除商品（真删除）
     * @param goodsId
     * @return 删除结果
     */
    @DeleteMapping("/{goodsId}")
    public ResultVo delete(@PathVariable Long goodsId) {
        if (goodsService.removeById(goodsId)) {
            return ResultVo.success("删除成功");
        }else {
            return ResultVo.error("删除失败");
        }
    }

    /**
     * 删除商品(伪删除)
     * @param goods
     * @return 删除结果
     */
    @PostMapping("/delete")
    public ResultVo delete(@RequestBody Goods goods) {
        UpdateWrapper<Goods> query = new UpdateWrapper<>();
        query.lambda()
                .set(Goods::getDeleteStatus, "1")
                .eq(Goods::getGoodsId, goods.getGoodsId());
        if (goodsService.update(query)) {
            return ResultVo.success("删除成功");
        }else {
            return ResultVo.error("删除失败");
        }
    }

    /**
     * 获取商品详情
     * @return 商品详情
     */
    @GetMapping("/list")
    public ResultVo getList(GoodsPage param) {
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        // 检查并添加类型条件（如果指定了类型）
        if (StringUtils.isNotEmpty(param.getType())) {
            queryWrapper.eq(Goods::getType, param.getType());
        }
        // 检查并添加标题模糊查询条件（如果指定了标题）
        if (StringUtils.isNotEmpty(param.getTitle())) {
            queryWrapper.like(Goods::getTitle, param.getTitle());
        }
        // 检查并添加用户名模糊查询条件（如果指定了用户名）
        if (StringUtils.isNotEmpty(param.getUsername())) {
            queryWrapper.like(Goods::getUserName, param.getUsername());
        }
        // 默认按照创建时间降序排序（不受前面条件影响）
        queryWrapper.orderByDesc(Goods::getCreateTime);
        // 创建分页对象
        Page<Goods> page = new Page<>(Optional.ofNullable(param.getCurrentPage()).orElse(1), param.getPageSize());
        // 执行分页查询
        IPage<Goods> pageList = goodsService.page(page, queryWrapper);
        // 返回结果
        return ResultVo.success(pageList);
    }

    /**
     * 设置商品热推
     */
    @PostMapping("/setIndex")
    public ResultVo setIndex(@RequestBody Goods goods) {
        LambdaUpdateWrapper<Goods> query = new LambdaUpdateWrapper<>();
        query.set(Goods::getSetIndex,goods.getSetIndex())
                .eq(Goods::getGoodsId,goods.getGoodsId());
        if (goodsService.update(query)) {
            return ResultVo.success("设置成功");
        }else {
            return ResultVo.error("设置失败");
        }
    }


    /**
     * 小程序推荐数据查询
     */
    @GetMapping("/getIndexList")
    public ResultVo getIndexList(GoodsList param) {
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getSetIndex, "1")
                .eq(Goods::getSellStatus, "0")
                .eq(Goods::getStatus, "0")
                .eq(Goods::getDeleteStatus, "0")
                .like(StringUtils.isNotEmpty(param.getKeywords()), Goods::getTitle, param.getKeywords())
                .orderByDesc(Goods::getCreateTime);// 默认按照创建时间降序排序
        // 创建分页对象
        IPage<Goods> page = new Page<>(Optional.ofNullable(param.getCurrentPage()).orElse(10), param.getPageSize());
        // 执行分页查询
        IPage<Goods> pageList = goodsService.page(page, queryWrapper);
        // 返回结果
        return ResultVo.success("查询成功",pageList);
    }

    /**
     * 小程序寻物和招领list查询
     */
    @GetMapping("/getGoodsList")
    public ResultVo getGoodsList(GoodsList param) {
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getType, param.getType())
                .eq(Goods::getSellStatus, "0")
                .eq(Goods::getStatus, "0")
                .eq(Goods::getDeleteStatus, "0")
                .like(StringUtils.isNotEmpty(param.getKeywords()), Goods::getTitle, param.getKeywords())
                .orderByDesc(Goods::getCreateTime);// 默认按照创建时间降序排序
        if (StringUtils.isNotEmpty(param.getCategoryId())) {
           queryWrapper.eq(Goods::getCategoryId, param.getCategoryId());
        }
        // 创建分页对象
        IPage<Goods> page = new Page<>(Optional.ofNullable(param.getCurrentPage()).orElse(10), param.getPageSize());
        // 执行分页查询
        IPage<Goods> pageList = goodsService.page(page, queryWrapper);
        // 返回结果
        return ResultVo.success("查询成功",pageList);
    }

    /**
     * 小程序寻物和招领详情查询
     * type 0寻物 1招领
     */
    @GetMapping("/getGoodsDetail")
    public ResultVo getGoodsDetail(Integer goodsId) {
        // 创建LambdaQueryWrapper
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getGoodsId, goodsId)
                .eq(Goods::getDeleteStatus, "0");
        // 执行查询
        Goods goods = goodsService.getOne(queryWrapper);
        // 返回结果
        return ResultVo.success("查询成功",goods);
    }

    /**
     * 小程序我的寻物和招领接口
     */
    @GetMapping("/getMyFindOrClaim")
    public ResultVo getMyFindOrClaim(GoodsPage parm) {
        // 构建分页对象
        IPage<Goods> page = new Page<>(parm.getCurrentPage(), parm.getPageSize());

        // 构建查询条件
        QueryWrapper<Goods> query = new QueryWrapper<>();
        query.lambda()
                .eq(Goods::getType, parm.getType())
                .eq(Goods::getUserId, parm.getUserId())
                .eq(Goods::getDeleteStatus, "0")
        .orderByDesc(Goods::getCreateTime);

        IPage<Goods> list = goodsService.page(page, query);

        return ResultVo.success("查询成功", list);
    }


    /**
     * 我的收藏
     */
    @GetMapping("/getMyCollect")
    public ResultVo getMyCollect(GoodsPage param) {
        IPage<Goods> list = goodsService.getMyCollect(param);
        return ResultVo.success("查询成功", list);
    }

    /**
     * 招领
     */
    @PostMapping("/hasClaimAndFind")
    public ResultVo hasClaimAndFind(@RequestBody Goods goods) {
        UpdateWrapper<Goods> query = new UpdateWrapper<>();
        query.lambda()
                .set(Goods::getSellStatus, "1")
                .set(Goods::getStatus, "1")
                .eq(Goods::getGoodsId, goods.getGoodsId());

        if (goodsService.update(query)) {
            return ResultVo.success("操作成功！");
        }

        return ResultVo.error("操作失败！");
    }

}
